//
//  VIPLiveVideoManager.m
//  TTProduct
//
//  Created by My mac on 2018/8/20.
//  Copyright © 2018年 TTProduct. All rights reserved.
//

#import "VIPIMManager.h"
#import "VIPPCH.h"

@interface VIPIMManager() <NIMLoginManagerDelegate, NIMChatManagerDelegate>

@property (strong, nonatomic) NIMSDK *nimSDK;
@property (weak, nonatomic) id<NIMLoginManager> loginManager;
@property (weak, nonatomic) id<NIMChatManager> chatManager;

@property (copy, nonatomic) VIPCompletionHandler autoLoginCompletion;
@property (copy, nonatomic) VIPCompletionHandler loginedLostConnection;

@end

@implementation VIPIMManager

- (void)registerSignalingSDK:(VIPSignalModel *)signal {
    _loginedLostConnection = nil;
    
    [super registerSignalingSDK:signal];
    
    NIMSDKOption *option = [NIMSDKOption optionWithAppKey:signal.appId];
    [[NIMSDK sharedSDK] registerWithOption:option];
}

- (void)loginCompletion:(VIPCompletionHandler)completion {
    self.status = VIPSignalStateLoginNO;
    _autoLoginCompletion = completion;
    NIMAutoLoginData *data = [NIMAutoLoginData new];
    data.account = self.signal.account;
    data.token = self.signal.token;
    data.forcedMode = YES;
    
    [_loginManager autoLogin:data];
    self.status = VIPSignalStateLogining;
}

- (void)onLogin:(NIMLoginStep)step {
    if (step == NIMLoginStepLinking ||
        step == NIMLoginStepLinkOK ||
        step == NIMLoginStepLogining ||
        step == NIMLoginStepSyncing ||
        step == NIMLoginStepSyncOK ||
        self.status == VIPSignalStateKiched)  {
        return;
    }
    
    [VIPWrite writeLogWithFormat:@"%s - vendor: %@, code: %d", __func__, self.signaingName, (int)step];
    
    VIPMessage *message = [self messageWithEcode:step];
    message.ecode = step;
    // 登陆成功
    if (step == NIMLoginStepLoginOK) {
        // 登陆后出现的问题(被踢)
        if (_loginedLostConnection) {
            _loginedLostConnection(message);
            return;
        }
        if (!_autoLoginCompletion) return ;
        _autoLoginCompletion(message);
        _autoLoginCompletion = nil;
        return;
    }
    // 登陆后出现的问题(被踢)
    if (_loginedLostConnection) {
        if (self.status != VIPSignalStateLogout) {
            self.status =  VIPSignalStateKiched; // 被踢
            _loginedLostConnection(message);
            return;
        }
        return;
    }
    self.status = VIPSignalStateLoginNO;
    // 登陆出现问题
    if (!_autoLoginCompletion) return ;
    _autoLoginCompletion(message);
    _autoLoginCompletion = nil;
}

- (void)onAutoLoginFailed:(NSError *)error {
    if (!_loginedLostConnection) return;
    VIPMessage *message = [VIPMessage messageWithFailedText:@"未知错误" status:VIPSignalCodeOther];
    _loginedLostConnection(message);
}

// 被踢 / 断开连接
- (void)loginedLostConnectionCompletion:(VIPCompletionHandler)completion {
    _loginedLostConnection = completion;
}

#pragma mark - <NIMLoginManagerDelegate>
// 被踢代理回调
- (void)onKick:(NIMKickReason)code clientType:(NIMLoginClientType)clientType {
    self.status = VIPSignalStateKiched;
    if (self.loginedLostConnection == nil){
        return;
    }
    
    VIPMessage *message = [self messageWithEcode:VIPSignalCodeKiched];
    self.loginedLostConnection(message);
}

- (void)sendMessageType:(NIMSessionType)type error:(NSError * __nullable *)error {
    NIMSession *session = [NIMSession session:self.signal.roomId type:type];
    // 构造出具体消息
    NIMMessage *message = [[NIMMessage alloc] init];
    NIMMessageSetting *setting = [NIMMessageSetting new];
    setting.persistEnable = NO;
    message.setting = setting;
    message.text = self.signal.msg;
    [_chatManager sendMessage:message toSession:session error:error];
}

- (void)logoutCompletion:(VIPCompletionHandler)completion {
    WS(weakSelf)
    self.status = VIPSignalStateLogout;
    [self.loginManager logout:^(NSError * _Nullable error) {
        [VIPWrite writeLogWithFormat:@"%s [loginManager logout] - vendor: %@",__func__, weakSelf.signaingName];
        
        VIPMessage *message = [weakSelf messageWithEcode:error.code];
        // 退出
        if (weakSelf.status == VIPSignalStateLogout && weakSelf.loginedLostConnection) {
            message.status = VIPSignalCodeLogout;
            weakSelf.loginedLostConnection(message);
            weakSelf.loginedLostConnection = nil;
            return;
        }
        if (!completion) return;
        completion(message);
    }];
}

#pragma mark - <NIMChatManagerDelegate>
// 接收消息
- (void)onRecvMessages:(NSArray<NIMMessage *> *)messages {
    if (self.status == VIPSignalStateLogout) return;
    if(self.response == nil) return;
    for (NIMMessage *message in messages) {
        NSString *msg = message.text;
        NSString *account = message.from;
        if (msg.length == 0) continue;
        self.response(account, msg, self.signaingName);
    }
}

- (VIPMessage *)messageWithEcode:(NSInteger)ecode {
    if(ecode == VIPSignalCodeSuccess || ecode == NIMLoginStepLoginOK) {
        if (self.status == VIPSignalStateLogout) {
            return [VIPMessage messageWithFailedText:@"用户退出" status:VIPSignalCodeLogout];
        }
        return nil;
    }
    
    if (ecode == VIPSignalCodeKiched) {
        return [VIPMessage messageWithFailedText:@"网易 : 在别的地方登陆" status:VIPSignalCodeKiched];
    }
    
    if (ecode == VIPSignalCodeTimeout && self.status == VIPSignalStateLogout) {
        return [VIPMessage messageWithFailedText:@"用户退出" status:VIPSignalCodeLogout];
    }
    
    if (ecode == NIMLoginStepLoseConnection && self.status != VIPSignalStateLogout) {
        return [VIPMessage messageWithFailedText:@"断开连接" status:VIPSignalStateLoseConnection];
    }
    
    if (ecode == NIMLocalErrorCodeInvalidParam) {
        return [VIPMessage messageWithFailedText:@"错误的参数" status:VIPSignalCodeLoginError];
    }
    
    return [VIPMessage messageWithFailedText:@"未知原因" status:VIPSignalCodeOther];
}

+ (instancetype)shareManager { return nil; }

- (void)setupIM {
    _nimSDK = [NIMSDK sharedSDK];
    
    
    
    NIMServerSetting *setting = [[NIMServerSetting alloc] init];
    setting.httpsEnabled = YES;
    [_nimSDK setServerSetting:setting];
    
    NIMSDKConfig *config = [NIMSDKConfig sharedConfig];
    config.enabledHttpsForInfo = YES;
    config.enabledHttpsForMessage = YES;
    [config setupSDKDir:[VIPPath nimLogPath]];
    config.maxAutoLoginRetryTimes = NSIntegerMax;
    
    _loginManager = [_nimSDK loginManager];
    _chatManager = [_nimSDK chatManager];
    
    [_loginManager addDelegate:self]; // NIMLoginManagerDelegate
    [_chatManager addDelegate:self]; // NIMChatManagerDelegate}
}

- (NSString *)flag {
    return @"N";
}

@end
